# CPU设计和分布式AI中的流水线思想
import argparse
import os

import shutil
import json
from py2neo import Graph, Relationship, Node
from colorama import Back, Style

BLOG_ROOT = "./data/blog"
BLOG_CACHE_ROOT = os.path.join(BLOG_ROOT, "cache")
LOG_CONFIG_FILE = "./config/neo4j.json"
meta_path = os.path.join(BLOG_ROOT, "meta.json")

def update_all_files():
    print(Back.BLUE, "[PUS]", Style.RESET_ALL, "将资源上传到服务器")
    os.system("scp -r data/blog root@101.43.239.71:/usr/local/go/ws/DustBE/data")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--src', type=str, help='需要的文章标题（在后端中，你可以认为文章的title是主键）')
    parser.add_argument('--dst', type=str, help='需要修改的标题名称')
    args = parser.parse_args()

    src = args.src.rstrip('.md')
    dst = args.dst.rstrip('.md')
    
    src_name = src + '.md'
    dst_name = dst + '.md'

    src_path = os.path.join(BLOG_ROOT, src_name)
    dst_path = os.path.join(BLOG_ROOT, dst_name)

    assert os.path.exists(src_path), f'源文件路径 {src_path} 不存在！'

    # 先修改本地的标题
    shutil.move(src_path, dst_path)

    # 修改meta文件
    with open(meta_path, 'r', encoding='utf-8') as fp:
        meta = json.load(fp)
    
    assert src in meta['index']
    dst_index = meta['index'].pop(src)
    meta['index'][dst] = dst_index

    meta['blog'][dst_index]['name'] = dst

    with open(meta_path, 'w', encoding='utf-8') as fp:
        json.dump(obj=meta, fp=fp, indent=4, ensure_ascii=False)
    
    # 偷个懒
    update_all_files()

    # 修改数据库
    # 登录数据库
    with open(LOG_CONFIG_FILE, "r", encoding="utf-8") as fp:
        c = json.load(fp)
    config = {
        "profile" : "http:" + c["url"].split(":")[1] + ":8002",
        "name" : c["name"],
        "password" : c["password"]
    }
    g = Graph(**config)

    g.run('match (n:Blog) where n.name="{}" set n.name="{}";'.format(
        src, dst
    ))